﻿using System;
using System.Reflection;
using System.Configuration;

namespace SDFL.Helper
{
    public class DllConfigHelper : IDisposable
    {
        private string _oldConfig;
        private bool _libCompat;
        private const string _newConfig = @"MyDll.config";
        // don't forget to rename this!!      
        internal DllConfigHelper()
        {
            _libCompat = Assembly.GetAssembly(typeof(ConfigurationManager)).GetName().Version.ToString().CompareTo("2.0.0.0") == 0;
            _oldConfig = AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString();
            Switch(_newConfig);
        }

        protected void Switch(string config)
        {
            if (_libCompat)
            {
                AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", config);
                FieldInfo[] fiStateValues = null;
                Type tInitState = typeof(ConfigurationManager).GetNestedType("InitState", BindingFlags.NonPublic);
                if (null != tInitState)
                    fiStateValues = tInitState.GetFields();
                FieldInfo fiInit = typeof(ConfigurationManager).GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static);
                FieldInfo fiSystem = typeof(ConfigurationManager).GetField("s_configSystem", BindingFlags.NonPublic | BindingFlags.Static);

                if (fiInit != null && fiSystem != null && null != fiStateValues)
                {
                    fiInit.SetValue(null, fiStateValues[1].GetValue(null));
                    fiSystem.SetValue(null, null);
                }
            }
        }

        public void Dispose()
        {
            Switch(_oldConfig);
        }

        public static string ConnectionString()
        {
            string cstr;
            using (new DllConfigHelper())
            {
                string str = AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString();
                cstr = ConfigurationManager.AppSettings["AlgorithmConfigFile"];
            }
            return cstr;
        }
    }//class
}
